package com.example.capsule_chat0322.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;

import com.example.capsule_chat0322.R;
import com.example.capsule_chat0322.bean.MessageBean;
import com.example.capsule_chat0322.bean.UserInfoBean;
import com.example.capsule_chat0322.configuration.Constant;
import com.example.capsule_chat0322.global.GlobalAssistMap;
import com.example.capsule_chat0322.global.LRUCache;
import com.example.capsule_chat0322.request.UserInfoRequest;
import com.example.capsule_chat0322.utils.AlterUtils;
import com.example.capsule_chat0322.utils.FileUtils;
import com.google.gson.Gson;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.net.URISyntaxException;
import java.util.Base64;

/**
 * @Author zhuzhiming
 * @Date 2022/5/5 15:19
 */
public class UpdateInfoActivity extends Activity {
    private Button select_pic_from_system;
    private Button select_pic_from_album;
    private Button update_info_cancel;
    private Button update_info_confirm;
    private EditText user_nickname;
    private EditText user_sign;
    private EditText user_sex;
    private EditText user_age;
    private EditText user_hobby;
    private EditText user_email;
    private ImageView user_avatar;
    private Bitmap bitmap;
    private String imagePath = null;
    private int imgId = -1;
    private static int ALBUM_RESULT_CODE = 0x999;
    public static final int SELECT_PIC = 1;
    private boolean avatarUpdate = false;
    private static final int UPDATE_INFO_CODE = 2;

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.update_info);

        select_pic_from_system = (Button) findViewById(R.id.select_pic_from_system);
        select_pic_from_album = (Button) findViewById(R.id.select_pic_from_album);
        update_info_cancel = findViewById(R.id.update_info_cancel);
        update_info_confirm = findViewById(R.id.update_info_confirm);
        user_avatar = (ImageView) findViewById(R.id.user_avatar);
        user_nickname = findViewById(R.id.user_nickname);
        user_sign = findViewById(R.id.user_sign);
        user_sex = findViewById(R.id.user_sex);
        user_age = findViewById(R.id.user_age);
        user_hobby = findViewById(R.id.user_hobby);
        user_email = findViewById(R.id.user_email);


        if (GlobalAssistMap.getObject("userInfo") != null) {

            UserInfoBean userInfoBean = (UserInfoBean) GlobalAssistMap.getObject("userInfo");
            user_nickname.setText(userInfoBean.getNickname());
            user_sign.setText(userInfoBean.getSign());
            user_sex.setText(userInfoBean.getSex() == -1 ? "" : userInfoBean.getSex() == 1 ? "男" : "女");
            user_age.setText(userInfoBean.getAge() == -1 ? "" : String.valueOf(userInfoBean.getAge()));
            user_hobby.setText(userInfoBean.getHobby());
            user_email.setText(userInfoBean.getEmail());

            String avatarStr = userInfoBean.getAvatarUrl();
            if (avatarStr.contains("/")) {

                LRUCache lruCache = (LRUCache) GlobalAssistMap.getObject("lruCache");
                Bitmap bitmap = (Bitmap) lruCache.get(avatarStr.substring(avatarStr.lastIndexOf("/")));
                //Bitmap bitmap = (Bitmap) GlobalAssistMap.getObject(avatarStr.substring(avatarStr.lastIndexOf("/")));
                if (bitmap == null) {
                    bitmap = BitmapFactory.decodeFile(avatarStr);
                    if (bitmap == null) {
                        UserInfoRequest.getAvatar(new Handler(new Handler.Callback() {
                            @Override
                            public boolean handleMessage(@NonNull Message message) {
                                String path = Constant.IMAGE_PATH + userInfoBean.getAvatarUrl().substring(userInfoBean.getAvatarUrl().lastIndexOf("/") + 1);
                                Bitmap bitmap = BitmapFactory.decodeFile(path);
                                lruCache.put(avatarStr.substring(avatarStr.lastIndexOf("/")), bitmap);
                                user_avatar.setImageBitmap(bitmap);
                                return true;
                            }
                        }), userInfoBean.getAvatarServerPath());
                    } else {
                        lruCache.put(avatarStr.substring(avatarStr.lastIndexOf("/")), bitmap);
                        user_avatar.setImageBitmap(bitmap);
                    }
                    //GlobalAssistMap.putObject(avatarStr.substring(avatarStr.lastIndexOf("/")), bitmap);
                } else {
                    user_avatar.setImageBitmap(bitmap);
                }
            } else {
                user_avatar.setImageResource(Integer.parseInt(avatarStr));
            }

        }


        if (ActivityCompat.checkSelfPermission(UpdateInfoActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(UpdateInfoActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        }

        select_pic_from_system.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(UpdateInfoActivity.this,
                        AvatarImagesActivity.class);
                startActivityForResult(intent, SELECT_PIC);

            }
        });


        select_pic_from_album.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openSysAlbum();
            }
        });

        update_info_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        update_info_confirm.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onClick(View view) {
                boolean isInValid = false;
                String nickname = user_nickname.getText().toString();

                if ("".equals(nickname) || nickname.length() > 12 || nickname.contains("(") || nickname.contains(")")) {
                    AlterUtils.alertByToastInMainThread((Context) GlobalAssistMap.getObject("context"), "请输入合法字符或长度(1-12)的昵称~");
                    user_nickname.setText("");
                    isInValid = true;
                }
                String sign = user_sign.getText().toString();
                if (sign.length() > 30) {
                    AlterUtils.alertByToastInMainThread((Context) GlobalAssistMap.getObject("context"), "个性签名最长30个字符~");
                    user_sign.setText("");
                    isInValid = true;
                }
                String sex = user_sex.getText().toString();
                if (!(sex.equals("男") || sex.equals("女") || sex.equals("male") || sex.equals("female")) && !"".equals(sex)) {
                    AlterUtils.alertByToastInMainThread((Context) GlobalAssistMap.getObject("context"), "请输入 男 女 male female 其中一个");
                    user_sex.setText("");
                    isInValid = true;
                }

                String age = user_age.getText().toString();
                if (!"".equals(age) && isNumber(age) && (Integer.parseInt(age) < 0 || Integer.parseInt(age) > 180)) {
                    AlterUtils.alertByToastInMainThread((Context) GlobalAssistMap.getObject("context"), "请输入合法的年龄");
                    user_age.setText("");
                    isInValid = true;
                }

                String hobby = user_hobby.getText().toString();
                if (hobby.length() > 30) {
                    AlterUtils.alertByToastInMainThread((Context) GlobalAssistMap.getObject("context"), "爱好最长30个字符~");
                    user_hobby.setText("");
                    isInValid = true;
                }

                String email = user_email.getText().toString();
                if (email.length() > 30) {
                    AlterUtils.alertByToastInMainThread((Context) GlobalAssistMap.getObject("context"), "email最长30个字符~");
                    user_email.setText("");
                    isInValid = true;
                }
                UserInfoBean userInfoBean = (UserInfoBean) GlobalAssistMap.getObject("userInfo");
                String avatarUrl = imagePath != null ? imagePath : imgId != -1 ? String.valueOf(imgId) : userInfoBean.getAvatarUrl();
                avatarUpdate = !avatarUrl.equals(userInfoBean.getAvatarUrl());

                if (!isInValid) {
                    userInfoBean = new UserInfoBean();
                    userInfoBean.setId(Integer.parseInt(GlobalAssistMap.getObject("userId").toString()));
                    userInfoBean.setNickname(nickname);
                    userInfoBean.setSign(sign);
                    if (!age.equals("")) {
                        userInfoBean.setAge(Integer.parseInt(age));
                    } else {
                        userInfoBean.setAge(-1);
                    }
                    if (!sex.equals("")) {
                        if (sex.equals("男") || sex.equals("male")) {
                            userInfoBean.setSex(1);
                        } else if (sex.equals("女") || sex.equals("female")) {
                            userInfoBean.setSex(0);
                        }
                    } else {
                        userInfoBean.setSex(-1);
                    }

                    userInfoBean.setHobby(hobby);
                    userInfoBean.setEmail(email);
                    userInfoBean.setAvatarUrl(avatarUrl);
                    UserInfoBean finalUserInfoBean = userInfoBean;

                    if (avatarUpdate && avatarUrl.contains("/")) {

                        byte[] data = null;

                        try {
                            FileInputStream inputStream = new FileInputStream(avatarUrl);
                            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
                            data = new byte[inputStream.available()];
                            bufferedInputStream.read(data);
                            bufferedInputStream.close();
                            inputStream.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        byte[] encode = new byte[0];
                        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                            encode = Base64.getEncoder().encode(data);
                        }

                        String bytes = new String(encode);
                        int length = bytes.length();
                        if (length > 600000) {
                            AlterUtils.alertByToastInMainThread(UpdateInfoActivity.this, "抱歉~图片过大,无法发送~");
                            return;
                        }
                        MessageBean messageBean = new MessageBean();
                        messageBean.setSenderId(String.valueOf(finalUserInfoBean.getId()));
                        messageBean.setContent(bytes);
                        messageBean.setFilePath(avatarUrl);

                        Handler handler = new Handler(new Handler.Callback() {
                            @Override
                            public boolean handleMessage(@NonNull Message message) {

                                String avatarServerPath = (String) message.obj;

                                if (avatarServerPath != null) {
                                    finalUserInfoBean.setAvatarServerPath(avatarServerPath);
                                }

                                Handler handler = new Handler(new Handler.Callback() {
                                    @Override
                                    public boolean handleMessage(@NonNull Message message) {
                                        String res = (String) message.obj;
                                        if (Constant.SUCCESS.equals(res)) {
                                            GlobalAssistMap.putObject("userInfo", finalUserInfoBean);
                                            GlobalAssistMap.putObject("update", Constant.SUCCESS);
                                            if (avatarUpdate) {
                                                GlobalAssistMap.putObject("avatarUpdate", "true");
                                            }
                                            Intent intent = new Intent();
                                            intent.putExtra("updateInfo", "");
                                            setResult(UPDATE_INFO_CODE, intent);
                                            finish();
                                        } else {
                                            GlobalAssistMap.putObject("update", Constant.FAIL);
                                        }
                                        return true;
                                    }
                                });
                                UserInfoRequest.doUpdateUserInfoRequest(handler, finalUserInfoBean);

                                return true;
                            }
                        });
                        UserInfoRequest.uploadAvatar(handler, new Gson().toJson(messageBean));
                    } else {
                        Handler handler = new Handler(new Handler.Callback() {
                            @Override
                            public boolean handleMessage(@NonNull Message message) {
                                String res = (String) message.obj;
                                if (Constant.SUCCESS.equals(res)) {
                                    GlobalAssistMap.putObject("userInfo", finalUserInfoBean);
                                    GlobalAssistMap.putObject("update", Constant.SUCCESS);
                                    if (avatarUpdate) {
                                        GlobalAssistMap.putObject("avatarUpdate", "true");
                                    }
                                    Intent intent = new Intent();
                                    intent.putExtra("updateInfo", "");
                                    setResult(UPDATE_INFO_CODE, intent);
                                    finish();
                                } else {
                                    GlobalAssistMap.putObject("update", Constant.FAIL);
                                }
                                return true;
                            }
                        });
                        UserInfoRequest.doUpdateUserInfoRequest(handler, userInfoBean);
                    }

                }

            }
        });

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (data != null) {
            if (requestCode == SELECT_PIC && resultCode == RESULT_OK) {
                imgId = data.getIntExtra("image", -1);
                //更换图片
                if (imgId != -1) {
                    user_avatar.setImageResource(imgId);
                }
            } else {
                handleImageOnKitKat(data);
            }
        }
    }


    private void openSysAlbum() {

        Intent albumIntent = new Intent(Intent.ACTION_PICK);

        albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");

        startActivityForResult(albumIntent, ALBUM_RESULT_CODE);

    }

    @TargetApi(value = 19)
    private void handleImageOnKitKat(Intent data) {


        Uri uri = data.getData();

        if (DocumentsContract.isDocumentUri(this, uri)) {

// 如果是document类型的Uri，则通过document id处理

            String docId = DocumentsContract.getDocumentId(uri);

            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {

                String id = docId.split(":")[1];

// 解析出数字格式的id

                String selection = MediaStore.Images.Media._ID + "=" + id;

                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);

            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {

                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content: //downloads/public_downloads"), Long.parseLong(docId));

                imagePath = getImagePath(contentUri, null);

            }

        } else if ("content".equalsIgnoreCase(uri.getScheme())) {

// 如果是content类型的Uri，则使用普通方式处理

            imagePath = getImagePath(uri, null);

        } else if ("file".equalsIgnoreCase(uri.getScheme())) {

// 如果是file类型的Uri，直接获取图片路径即可

            imagePath = uri.getPath();

        }

// 根据图片路径显示图片

        displayImage(imagePath);

        System.out.println(imagePath);

    }

    /**
     * 获取图片的路径
     */

    @SuppressLint("Range")
    private String getImagePath(Uri uri, String selection) {

        String path = null;

        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);

        if (cursor != null) {

            if (cursor.moveToFirst()) {

                try {
                    path = FileUtils.getPath(UpdateInfoActivity.this, uri);
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                }

            }

            cursor.close();

        }

        return path;

    }

    /**
     * 展示图片
     */

    private void displayImage(String imagePath) {

        Bitmap bitmap = BitmapFactory.decodeFile(imagePath);

        user_avatar.setImageBitmap(bitmap);

    }


    @RequiresApi(api = Build.VERSION_CODES.N)
    private static boolean isNumber(final String str) {
        // null or empty
        if (str == null || str.length() == 0) {
            return true;
        }
        return str.chars().allMatch(Character::isDigit);
    }


}
